<?php
/**
 *
 * User: 罗艳忠
 * Email:luozong05@126.com
 * DateTime: 2017/5/4 11:02
 */

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Session;
use Validator;


class FileController extends Controller
{
    /**
     * Create a new controller instance.
     *
     */
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
        //$this->response = $response;

    }

    public function imageupload(){
        $this->wrongTokenAjax();
        $file = $this->request->file('image');
        //$input = array('image' => $file);

        $rules = array(
            'image' => 'image'
        );

        $validator = Validator::make($this->request->allFiles(), $rules);
        if ( $validator->fails() ) {
            return response()->json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ]);
        }

        $destinationPath = 'uploads/'.date("Y/md/");

        $fileext = $file->getClientOriginalExtension();
        $filename = time() . "." . $fileext;
        $file->move($destinationPath, $filename);

        return response()->json([
            'success' => true,
            'path' => $destinationPath.$filename,
        ]);
    }


    public function wrongTokenAjax()
    {
        if ( Session::token() !== $this->request->get('_token') ) {
            $response = [
                'status' => false,
                'errors' => 'Wrong Token',
            ];
            return Response::json($response);
        }

    }
}